/**
 * PetRenderer - 宠物渲染器
 * 负责在Canvas上绘制宠物的所有部位和动画
 */

import DrawingEngine from './DrawingEngine.js'
import AnimationManager from './AnimationManager.js'
import OptimizationManager from './OptimizationManager.js'

class PetRenderer {
  constructor(ctx, options = {}) {
    this.ctx = ctx
    this.options = {
      width: options.width || 100,
      height: options.height || 100,
      pixelRatio: options.pixelRatio || 1,
      debugMode: options.debugMode || false,
      colorScheme: options.colorScheme || {
        primary: '#667eea',
        secondary: '#764ba2',
        accent: '#ffffff'
      }
    }
    
    this.drawingEngine = new DrawingEngine(ctx)
    this.animationManager = new AnimationManager()
    this.optimizationManager = new OptimizationManager()
    this.currentAnimation = 'idle'
    this.isDragging = false
    
    // 宠物尺寸配置
    this.petSize = {
      bodyRadius: 35,
      earWidth: 9,
      earHeight: 11,
      eyeRadius: 5,
      pupilRadius: 2.5,
      mouthWidth: 7,
      mouthHeight: 3.5,
      limbWidth: 5,
      limbHeight: 9,
      tailWidth: 4,
      tailHeight: 12
    }
    
    // 中心位置
    this.centerX = this.options.width / 2
    this.centerY = this.options.height / 2
  }

  /**
   * 主渲染方法
   */
  render(timestamp, deltaTime) {
    // 清空画布
    this.drawingEngine.clearAll(this.options.width, this.options.height)
    
    // 获取当前动画帧
    const frame = this.animationManager.getCurrentFrame(timestamp)
    
    // 应用全局变换
    this.drawingEngine.save()
    this.drawingEngine.translate(this.centerX, this.centerY)
    
    // 应用身体变换
    const bodyY = frame.body?.y || 0
    const bodyRotation = (frame.body?.rotation || 0) * Math.PI / 180
    const bodyScale = frame.body?.scale || 1
    
    this.drawingEngine.translate(0, bodyY)
    this.drawingEngine.rotate(bodyRotation)
    this.drawingEngine.scale(bodyScale, bodyScale)
    
    // 绘制各部位（从后往前）
    this.drawTail(frame)
    this.drawLimbs(frame)
    this.drawBody(frame)
    this.drawEars(frame)
    this.drawEyes(frame)
    this.drawMouth(frame)
    
    this.drawingEngine.restore()
    
    // 调试模式
    if (this.options.debugMode) {
      this.drawDebugInfo(frame, timestamp)
    }
    
    // 绘制完成后调用draw
    this.ctx.draw(false, () => {
      // 绘制完成回调
    })
  }

  /**
   * 绘制宠物身体
   */
  drawBody(frame) {
    const radius = this.petSize.bodyRadius
    
    // 根据性能优化决定是否使用渐变
    let fillStyle
    if (this.optimizationManager.shouldSimplifyGradients()) {
      fillStyle = this.options.colorScheme.primary
    } else {
      fillStyle = this.drawingEngine.createLinearGradient(
        -radius, -radius,
        radius, radius,
        [
          { offset: 0, color: this.options.colorScheme.primary },
          { offset: 1, color: this.options.colorScheme.secondary }
        ]
      )
    }
    
    // 根据性能优化决定是否绘制阴影
    if (!this.optimizationManager.shouldDisableShadows()) {
      this.drawingEngine.setShadow(0, 3, 10, 'rgba(102, 126, 234, 0.3)')
    }
    
    // 绘制身体
    this.drawingEngine.drawCircle(0, 0, radius, fillStyle, {
      fill: true
    })
    
    this.drawingEngine.clearShadow()
    
    // 绘制光泽效果（非必要，低性能时跳过）
    if (!this.optimizationManager.shouldDisableNonEssentialAnimations()) {
      this.drawingEngine.save()
      this.drawingEngine.setAlpha(0.3)
      this.drawingEngine.drawCircle(-10, -10, 10, this.options.colorScheme.accent, {
        fill: true
      })
      this.drawingEngine.restore()
    }
  }

  /**
   * 绘制耳朵
   */
  drawEars(frame) {
    const earWidth = this.petSize.earWidth
    const earHeight = this.petSize.earHeight
    const bodyRadius = this.petSize.bodyRadius
    
    // 左耳
    this.drawingEngine.save()
    const leftRotation = (frame.ears?.left?.rotation || -15) * Math.PI / 180
    this.drawingEngine.translate(-bodyRadius + 18, -bodyRadius + 8)
    this.drawingEngine.rotate(leftRotation)
    
    this.drawEar(earWidth, earHeight)
    this.drawingEngine.restore()
    
    // 右耳
    this.drawingEngine.save()
    const rightRotation = (frame.ears?.right?.rotation || 15) * Math.PI / 180
    this.drawingEngine.translate(bodyRadius - 18, -bodyRadius + 8)
    this.drawingEngine.rotate(rightRotation)
    
    this.drawEar(earWidth, earHeight)
    this.drawingEngine.restore()
  }

  /**
   * 绘制单个耳朵
   */
  drawEar(width, height) {
    const gradient = this.drawingEngine.createLinearGradient(
      -width, -height,
      width, height,
      [
        { offset: 0, color: this.options.colorScheme.primary },
        { offset: 1, color: this.options.colorScheme.secondary }
      ]
    )
    
    this.drawingEngine.setShadow(0, 1, 4, 'rgba(102, 126, 234, 0.2)')
    
    // 绘制椭圆形耳朵
    this.ctx.beginPath()
    this.ctx.ellipse(0, 0, width, height, 0, 0, Math.PI * 2)
    this.ctx.setFillStyle(gradient)
    this.ctx.fill()
    
    this.drawingEngine.clearShadow()
  }

  /**
   * 绘制眼睛
   */
  drawEyes(frame) {
    const eyeRadius = this.petSize.eyeRadius
    const pupilRadius = this.petSize.pupilRadius
    const eyeScale = frame.eyes?.scale || 1
    
    // 左眼
    this.drawingEngine.save()
    this.drawingEngine.translate(-20, -10)
    this.drawingEngine.scale(eyeScale, eyeScale)
    this.drawEye(eyeRadius, pupilRadius)
    this.drawingEngine.restore()
    
    // 右眼
    this.drawingEngine.save()
    this.drawingEngine.translate(20, -10)
    this.drawingEngine.scale(eyeScale, eyeScale)
    this.drawEye(eyeRadius, pupilRadius)
    this.drawingEngine.restore()
  }

  /**
   * 绘制单个眼睛
   */
  drawEye(eyeRadius, pupilRadius) {
    // 眼白
    this.drawingEngine.setShadow(0, 0.5, 1.5, 'rgba(0, 0, 0, 0.1)')
    this.drawingEngine.drawCircle(0, 0, eyeRadius, this.options.colorScheme.accent, {
      fill: true
    })
    this.drawingEngine.clearShadow()
    
    // 瞳孔
    this.drawingEngine.drawCircle(0, 0, pupilRadius, '#333', {
      fill: true
    })
  }

  /**
   * 绘制嘴巴
   */
  drawMouth(frame) {
    const mouthWidth = this.petSize.mouthWidth
    const mouthHeight = this.petSize.mouthHeight
    const curve = frame.mouth?.curve || 0.5
    
    // 根据curve值调整嘴巴形状
    // curve: 0=sad, 0.5=neutral, 1=happy
    const curvature = (curve - 0.5) * mouthHeight * 2
    
    this.ctx.beginPath()
    this.ctx.moveTo(-mouthWidth, 9)
    this.ctx.quadraticCurveTo(0, 9 + curvature, mouthWidth, 9)
    this.ctx.setStrokeStyle('#333')
    this.ctx.setLineWidth(1)
    this.ctx.setLineCap('round')
    this.ctx.stroke()
  }

  /**
   * 绘制四肢
   */
  drawLimbs(frame) {
    const limbWidth = this.petSize.limbWidth
    const limbHeight = this.petSize.limbHeight
    const bodyRadius = this.petSize.bodyRadius
    const offset = frame.limbs?.offset || 0
    
    // 左前肢
    this.drawingEngine.save()
    this.drawingEngine.translate(-18, bodyRadius - 8 + offset)
    this.drawLimb(limbWidth, limbHeight)
    this.drawingEngine.restore()
    
    // 右前肢
    this.drawingEngine.save()
    this.drawingEngine.translate(18, bodyRadius - 8 - offset)
    this.drawLimb(limbWidth, limbHeight)
    this.drawingEngine.restore()
  }

  /**
   * 绘制单个肢体
   */
  drawLimb(width, height) {
    const gradient = this.drawingEngine.createLinearGradient(
      -width, 0,
      width, height,
      [
        { offset: 0, color: this.options.colorScheme.primary },
        { offset: 1, color: this.options.colorScheme.secondary }
      ]
    )
    
    this.drawingEngine.setShadow(0, 1, 3, 'rgba(102, 126, 234, 0.2)')
    this.drawingEngine.drawRoundRect(-width/2, 0, width, height, width/2, gradient, {
      fill: true
    })
    this.drawingEngine.clearShadow()
  }

  /**
   * 绘制尾巴
   */
  drawTail(frame) {
    const tailWidth = this.petSize.tailWidth
    const tailHeight = this.petSize.tailHeight
    const bodyRadius = this.petSize.bodyRadius
    const rotation = (frame.tail?.rotation || 25) * Math.PI / 180
    
    this.drawingEngine.save()
    this.drawingEngine.translate(bodyRadius - 8, 20)
    this.drawingEngine.rotate(rotation)
    
    const gradient = this.drawingEngine.createLinearGradient(
      -tailWidth, 0,
      tailWidth, tailHeight,
      [
        { offset: 0, color: this.options.colorScheme.primary },
        { offset: 1, color: this.options.colorScheme.secondary }
      ]
    )
    
    this.drawingEngine.setShadow(0, 1, 4, 'rgba(102, 126, 234, 0.2)')
    this.drawingEngine.drawRoundRect(-tailWidth/2, 0, tailWidth, tailHeight, tailWidth/2, gradient, {
      fill: true
    })
    this.drawingEngine.clearShadow()
    
    this.drawingEngine.restore()
  }

  /**
   * 绘制调试信息
   */
  drawDebugInfo(frame, timestamp) {
    const fps = Math.round(1000 / (timestamp - (this.lastTimestamp || timestamp)))
    this.lastTimestamp = timestamp
    
    this.drawingEngine.drawText(
      `FPS: ${fps}`,
      5, 5,
      '#000',
      { fontSize: 10, align: 'left' }
    )
    
    this.drawingEngine.drawText(
      `Anim: ${this.currentAnimation}`,
      5, 20,
      '#000',
      { fontSize: 10, align: 'left' }
    )
  }

  /**
   * 更新动画状态
   */
  updateAnimation(animationType, timestamp) {
    if (animationType !== this.currentAnimation) {
      this.currentAnimation = animationType
      this.animationManager.switchAnimation(animationType, timestamp || performance.now())
    }
  }

  /**
   * 设置拖拽状态
   */
  setDragging(isDragging, timestamp) {
    this.isDragging = isDragging
    if (isDragging) {
      this.updateAnimation('dragging', timestamp)
    }
  }

  /**
   * 设置颜色方案
   */
  setColorScheme(colorScheme) {
    this.options.colorScheme = { ...this.options.colorScheme, ...colorScheme }
  }

  /**
   * 获取动画管理器
   */
  getAnimationManager() {
    return this.animationManager
  }

  /**
   * 获取优化管理器
   */
  getOptimizationManager() {
    return this.optimizationManager
  }

  /**
   * 应用性能优化
   */
  applyOptimization(fps) {
    const result = this.optimizationManager.autoAdjustStrategy(fps)
    if (result) {
      console.log('Performance optimization applied:', result)
      return result
    }
    return null
  }

  /**
   * 销毁渲染器
   */
  destroy() {
    this.drawingEngine = null
    this.animationManager = null
    this.optimizationManager = null
    this.ctx = null
  }
}

export default PetRenderer
